package ru.rs.framework.interfaces.impl;

import java.io.IOException;
import java.io.InputStream;

import ru.rs.framework.interfaces.Graphics;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Rect;

public class GraphicsImpl implements Graphics {
	private AssetManager assets;
	private Bitmap frame;
	private Canvas canvas;

	private Rect src = new Rect();
	private Rect dst = new Rect();

	public GraphicsImpl(AssetManager manager, Bitmap fr) {
		assets = manager;
		frame = fr;
		canvas = new Canvas(frame);
	}

	@Override
	public Bitmap newBitmap(String fileName) {
		InputStream in = null;
		Bitmap bm = null;
		try {
			in = assets.open(fileName);
			bm = BitmapFactory.decodeStream(in);
			if (bm == null) {
				throw new RuntimeException("No image " + fileName + " found!");
			}
		} catch (IOException e) {
			throw new RuntimeException("No image " + fileName + " found!");
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
				}
			}
		}
		return bm;
	}

	@Override
	public void drawBitmap(Bitmap bm, int x, int y) {
		canvas.drawBitmap(bm, x, y, null);
	}

	@Override
	public void drawBitmap(Bitmap bm, int x, int y, int srcX, int srcY, int w,
			int h) {
		src.left = srcX;
		src.top = srcY;
		src.right = srcX + w - 1;
		src.bottom = srcY + h - 1;

		dst.left = x;
		dst.right = x + w - 1;
		dst.top = y;
		dst.bottom = y + h - 1;
		canvas.drawBitmap(bm, src, dst, null);
	}

	@Override
	public void clear(int color) {
		canvas.drawColor(color);
	}

	@Override
	public int getWidth() {
		return frame.getWidth();
	}

	@Override
	public int getHeight() {
		return frame.getHeight();
	}

}
